package com.slaffka.controllers;

import com.slaffka.model.Page;
import com.slaffka.model.PageType;
import com.slaffka.model.notification.Notification;
import com.slaffka.model.notification.NotificationDTO;
import com.slaffka.model.user.User;
import com.slaffka.services.ServiceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by IntelliJ IDEA.
 * _User: v.tsapaev
 * Date: 15.02.12
 * Time: 19:13
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/app")
public class HomeController {
    private static final Logger LOG = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    ServiceFactory service;

    @Autowired
    @Qualifier("authenticationManager")
    AuthenticationManager authenticationManager;
    
    HomeController(){
        
    }
    
    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    public @ResponseBody String getUsers(){
        LOG.info("***getUsers");
        return "aaaaaa";
    }

    @RequestMapping(value = "/auth", method = RequestMethod.POST, headers = {"content-type=application/json"})
    public @ResponseBody String auth(@RequestBody User user, HttpServletRequest request){
        System.out.println("***auth");
        HttpSession session = request.getSession();


        System.out.println("setsessionattribut = " + session.getAttribute("user"));

//        ///////
//        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
//        token.setDetails(user);
//        try {
//            Authentication auth = authenticationManager.authenticate(token);
//            SecurityContextHolder.getContext().setAuthentication(auth);

            if (session.getAttribute("user") == null && user != null){
                service.getUserSessionService().authUser(user, session);
            }
//            LOG.info("auth: success");
//        } catch (BadCredentialsException e) {
//            LOG.info("auth: error");
//        }
        return ((User)session.getAttribute("user")).getUsername().toString();
    }

    @RequestMapping(value = "/unauth", method = RequestMethod.POST)
    public @ResponseBody String unauth(HttpServletRequest request){
        System.out.println("***auth");
        HttpSession session = request.getSession();
        service.getUserSessionService().unauthUser(session);
       // session.removeAttribute("user");

        return "";
    }

    @RequestMapping(value = "/checkNotifications", method = RequestMethod.POST /*, headers="Content-Type=application/json"*/)
    public @ResponseBody List<NotificationDTO> checkNotifications(HttpServletRequest request){
        LOG.debug("checkNotifications");
//        Message message = new Message();
//        message.setText("test");
//        message.setTitle("testttt");
//        System.out.println("***message = " + message);
//        return message;

        HttpSession session = request.getSession();
        LOG.debug("***session = " + session);
        LOG.debug("***session = " + session.getId());
        List<Object> notifications = service.getNotificationService().getAllClientNotifications(session.getId());
        List<NotificationDTO> notificationList = new ArrayList<NotificationDTO>();
//        List<Message> messages = new ArrayList<Message>();
//        String mes = null;
//        Message message = null;
        Notification n = null;
        for (Object notification: notifications){
            LOG.debug("~~~~~~~system.message" + notification.getClass());
            notificationList.add(NotificationDTO.convertToDTO((Notification) notification));
            n = (Notification)notification;
            LOG.debug("~~~n = " + n);
//            if (notification instanceof Message){
//                message = (Message)notification;
//                System.out.println("~~~~~~~~~message = " + message);
//                mes = ((Message)notification).getText();
//            }
        }

        return notificationList;
    }

    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
    public @ResponseBody
    NotificationDTO sendMessage(@RequestParam String message, HttpServletRequest request){
        System.out.println("***sendMessage");
        HttpSession session = request.getSession();
        Notification notification = service.getNotificationService().sendMessage(message, session);
        return NotificationDTO.convertToDTO(notification);
    }

//    @GET
//    @Path(value = "/ajax/add.do")
//    public String add() {
//        System.out.println("~~~~~~ok");
//        Collection<XMLElement> contacts = new ArrayList<XMLElement>();
//
//        Collection<_User> users = service.getUsers();
//        for(_User currentUser:users)
//        {
//            contacts.add(new XMLElement(currentUser.getId(),currentUser.getLastName()));
//        }
//        return new XMLList(contacts);
//        return "aaaa";
//    }
//
//    @GET
//    @Path(value = "/ajax/ok.do")
//    @Produces("text/plain")
//    public void getBasic(final @Suspend(1000) AsynchronousResponse response) throws Exception {
//        System.out.println("~~~~~~~~~~before ok");
//        Thread t = new Thread()
//        {
//            @Override
//            public void run()
//            {
//                try
//                {
//                    System.out.println("~~~~~~~~~~~~~ok1");
//                    Response jaxrs = Response.ok("ok.do").type(MediaType.TEXT_PLAIN).build();
//                    System.out.println("~~~~~~~~~~~~~ok2, response = " + response + ", jaxrs = " + jaxrs);
//                    response.setResponse(jaxrs);
//                    System.out.println("~~~~~~~~~~~~~ok3");
//                }
//                catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//            }
//        };
//        t.start();
//    }

    @RequestMapping(value = "/{url}")
    public String home(@PathVariable String url, Model model) {
        model.addAttribute(new User());
        //userService = new UserServiceImpl();
//        Page page = new Page();
//        page.setName("Admin");
//        page.setPageType(PageType.ADMIN);
//        page.setUrl("admin");
//        service.getPageService().createPage(page);
        System.out.println("HomeController: Passing through..., url = " + url);
        System.out.println("*****themeService = " + service.getThemeService().getThemeList());
        Page currentPage = service.getPageService().getPageByUrl(url);
        List<Page> pages = service.getPageService().getAllApplicationPages();
        model.addAttribute("pages", pages);
        model.addAttribute("currentPage", currentPage);
        System.out.println("~~~~pages = " + pages + "***page = " + currentPage);


        if (currentPage != null && PageType.ADMIN.equals(currentPage.getPageType())){
            return "admin";
        }


        
//        _User user = service.getUserService().getUserById(new Long(1));
//        System.out.println("user = " + user.getName());
//        model.addAttribute("hello", "hi");
//        List<_User> users = service.getUserService().getAllUsers();
//        model.addAttribute("users", users);
//        List<Page> pages = service.getPageService().getAllApplicationPages();
//        Page currentPage = service.getPageService().getPageByUrl(url);
//        if ("admin".equals(currentPage.getName()))
//        System.out.println("***page = " + pages);
//        model.addAttribute("pages", pages);


        return "index";
    }        
}
